<template>
  <el-drawer v-model="open" size="45%" :show-close="false" @open="openDrawer" @close="closeDrawer" destroy-on-close>
    <template #title>
      <h2><svg-icon icon-class="list"></svg-icon><span style="padding-left: 15px">知识库管理</span></h2>
    </template>
    <template #default>
      <el-form :model="form" ref="addRef" :rules="formRules" label-width="140px" v-loading="drawerLoading"
        :scroll-to-error="true" :disabled="type == '0'">
        <el-form-item label="标签" prop="label">
          <el-space wrap class="label-space">
            <el-input v-model="form.label" clearable readonly></el-input>
            <el-button type="primary" @click="labelOpen = true">选择</el-button>
          </el-space>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" clearable></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author" placeholder="多个作者请用顿号隔开">
          <el-input v-model="form.author" clearable></el-input>
        </el-form-item>
        <el-form-item label="发表年份" prop="yearOfPublication">
          <el-input v-model.number="form.yearOfPublication" v-inputNumber="0" clearable></el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="keyword" placeholder="多个关键词请用顿号隔开">
          <el-input v-model="form.keyword" clearable></el-input>
        </el-form-item>
        <el-form-item label="原文链接" prop="chaining">
          <el-input v-model="form.chaining" clearable></el-input>
        </el-form-item>
        <el-form-item label="期刊来源" prop="source">
          <el-input v-model="form.source" clearable></el-input>
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="form.summary" resize="none" :autosize="{ minRows: 5, maxRows: 12 }" type="textarea" show-word-limit
            maxlength="500" clearable></el-input>
        </el-form-item>
        <el-form-item label="文章描述" prop="description">
          <el-input v-model="form.description" resize="none" :autosize="{ minRows: 5, maxRows: 12 }" type="textarea" show-word-limit
            maxlength="500" clearable></el-input>
        </el-form-item>
        <el-form-item label="总结分享" prop="sumup">
          <el-input v-model="form.sumup" resize="none" :autosize="{ minRows: 5, maxRows: 12 }" type="textarea" show-word-limit
            maxlength="500" clearable></el-input>
        </el-form-item>
        <el-form-item label="附件上传" prop="entitity">
          <FileUpload v-model="form.entitity" :limit="1" :fileType="['doc', 'docx', 'pdf', 'ofd']"
            @uploadFile="uploadSuccess" @delFile="deleteFile" />
            <el-link type="danger" :underline="false">（保护知识产权，所有分享资料仅供内部交流使用，不得用于任何商业用途，产生侵权行为由本人负责！）</el-link>
        </el-form-item>
        <el-form-item label="查看权限" prop="permission" v-if="type == '2'">
          <el-row style="width: 100%">
            <el-space direction="vertical" alignment="normal">
              <el-space>
                <el-icon>
                  <DArrowRight />
                </el-icon>
                <span>本省</span>
              </el-space>
              <el-radio-group v-model="form.permission">
                <el-radio label="0">本省所有用户</el-radio>
                <el-radio label="1">省级管理员</el-radio>
              </el-radio-group>
            </el-space>
          </el-row>
          <el-row style="width: 100%">
            <el-space direction="vertical" alignment="normal">
              <el-space>
                <el-icon>
                  <DArrowRight />
                </el-icon>
                <span>其他</span>
              </el-space>
              <el-radio-group v-model="form.permission" @change="permissionChange">
                <el-radio label="2">全国所有用户</el-radio>
                <el-radio label="3">国家级管理员</el-radio>
                <el-radio label="4">
                  <template #default>
                    <span @click="openSelect = true">用户选择</span>
                  </template>
                </el-radio>
              </el-radio-group>
            </el-space>
          </el-row>
          <el-row style="width: 100%" v-if="form.users?.length > 0">
            <el-table :data="form.users" border class="normal-table">
              <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
              <el-table-column prop="unit" label="单位" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="{ row }">
                  <el-button type="text" @click="delectUser(row.userId)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-form-item>
      </el-form>
    </template>
    <template #footer v-if="type != '0'">
      <div style="text-align: center">
        <el-button type="primary" @click="saveForm">提交</el-button>
        <el-button plain @click="closeDrawer">取消</el-button>
      </div>
    </template>
  </el-drawer>
  <LabelManage v-model:open="labelOpen" v-model:name="form.label" :role="role" />
  <SelectUser ref="selectRef" :multi="2" v-model:show="openSelect" @getSelectList="getSelectList" />
</template>
<script setup>
import LabelManage from './labelManage.vue'
import SelectUser from '@/components/SelectUser'
import { save, getById, update } from '@/api/knowledgeManage'
import { nextTick } from 'vue';

const props = defineProps({
  open: Boolean,
  id: {
    type: String,
    default: ''
  },
  type: String
})
const emits = defineEmits(['update:open', 'update:id', 'updateList'])
const { proxy } = getCurrentInstance()
const initForm = () => ({permission: '0'})
const data = reactive({
  drawerLoading: false,
  form: initForm()
})
const { drawerLoading, form } = toRefs(data)
const addRef = ref()
const formRules = {
  label: [{ required: true, message: '请填写标签！', trigger: 'change' }],
  title: [{ required: true, message: '请填写文章标题！', trigger: 'blur' }],
  author: [{ required: true, message: '请填写作者！', trigger: 'blur' }]
}
const labelOpen = ref(false)
const role = props.type == '2' ? '0' : '1'

// 用户选择-人员弹窗
const openSelect = ref(false)
const permissionChange = (val) => {
  if (val == 4) {
    openSelect.value = true
  }
}
const getSelectList = (arr) => {
  form.value.users = arr.map(item => {
    return {
      userId: item.orgUser.userId,
      userName: item.realName,
      unit: item.orgName
    }
  })
}
const delectUser = (userId) => {
  form.value.users = form.value.users.filter(item => item.userId != userId)
}
// 保存
const saveForm = () => {
  addRef.value.validate(valid => {
    if (valid) {
      if (form.value.id) {
        update(form.value).then(res => {
          proxy.$modal.msgSuccess('修改成功！')
          emits('updateList')
          closeDrawer()
        })
      } else {
        save(form.value).then(res => {
          proxy.$modal.msgSuccess('添加成功！')
          emits('updateList')
          closeDrawer()
        })
      }
    }
  })
}
const openDrawer = () => {
  nextTick(() => {
    proxy.$refs['addRef'].clearValidate()
  })
  props.id && getById(props.id).then(res => {
    form.value = res.data
  })
}
const closeDrawer = () => {
  emits('update:open', false)
  emits('update:id', '')
  proxy.resetAllForm(form.value, initForm())
}
// 附件
const uploadSuccess = (data) => {
  form.value.fileid = data.map(item => item.attachId).join(',')
}
const deleteFile = (data) => {
  form.value.fileid = data
}
onMounted(() => {
  if(props.type == '1'){
    form.value.permission = '5'
  }
})
</script>
<style scoped lang="scss">
.label-space {
  color: red;
  width: 100%;

  &.el-space {
    :deep(.el-space__item) {
      &:first-child {
        width: calc(100% - 70px);
      }

      &:last-child {
        margin-right: 0 !important;
      }
    }
  }
}
</style>